package health

import (
	"errors"
	"gitee.com/g-qs/gin-vue-admin/server/global"
	"gitee.com/g-qs/gin-vue-admin/server/model/common/request"
	"gitee.com/g-qs/gin-vue-admin/server/model/health"
	healthReq "gitee.com/g-qs/gin-vue-admin/server/model/health/request"
	"gitee.com/g-qs/gin-vue-admin/server/model/user"
	"gorm.io/gorm"
)

type HealthQuestionService struct {
}

// CreateHealthQuestion 创建健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) CreateHealthQuestion(hq *health.HealthQuestion) (err error) {
	err = global.GVA_DB.Create(hq).Error
	return err
}

// DeleteHealthQuestion 删除健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) DeleteHealthQuestion(hq health.HealthQuestion) (err error) {
	err = global.GVA_DB.Delete(&hq).Error
	return err
}

// DeleteHealthQuestionByIds 批量删除健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) DeleteHealthQuestionByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]health.HealthQuestion{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateHealthQuestion 更新健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) UpdateHealthQuestion(hq health.HealthQuestion) (err error) {
	err = global.GVA_DB.Save(&hq).Error
	return err
}

// GetHealthQuestion 根据id获取健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) GetHealthQuestion(id uint) (hq health.HealthQuestion, err error) {
	err = global.GVA_DB.Where("id = ?", id).Preload("User").First(&hq).Error
	return
}

// GetHealthQuestionInfoList 分页获取健康问答-待回答问题表记录
// Author [piexlmax](https://github.com/piexlmax)
func (hqService *HealthQuestionService) GetHealthQuestionInfoList(info healthReq.HealthQuestionSearch) (list []health.HealthQuestion, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&health.HealthQuestion{})
	var hqs []health.HealthQuestion
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	var userInfo user.User
	if info.Name != "" {
		err = global.GVA_DB.Model(&user.User{}).Where("name LIKE ?", "%"+info.Name+"%").First(&userInfo).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			db = db.Where("uid = 0")
		} else {
			db = db.Where("uid = ?", userInfo.ID)
		}
	}
	if info.Question != "" {
		db = db.Where("question LIKE ?", "%"+info.Question+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Preload("User").Find(&hqs).Error
	return hqs, total, err
}
